package com.gr.catanddog_common.utils;

import com.alibaba.fastjson.JSON;
import com.gr.catanddog_common.damin.User;
import com.gr.catanddog_common.utils.tokenUtils.TokenHeader;
import com.gr.catanddog_common.utils.tokenUtils.TokenPlayLoad;
import com.gr.catanddog_common.utils.tokenUtils.TokenSignature;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
@Data
public class Token {


    public static <M> String tokenUtil(M data, User user,Long time) throws NoSuchAlgorithmException, InvalidKeyException {
        TokenPlayLoad<M> playLoad = new TokenPlayLoad<M>();
        SimpleDateFormat formatter = new SimpleDateFormat();
        playLoad.setAud(user.getUserName());
        long times = new Date().getTime();
        playLoad.setIat(String.valueOf(times));
        playLoad.setExp(String.valueOf(times+time));
        playLoad.setData(data);
        TokenHeader header = new TokenHeader();
        TokenSignature signature = new TokenSignature(playLoad, header);
        return Base64.getEncoder().encodeToString(JSON.toJSONBytes(header))
                +'.'+Base64.getEncoder().encodeToString(JSON.toJSONBytes(playLoad))
                +'.'+signature.getSignature();
    }

}
